package com.example.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.system.dto.SleepDuration;
import com.example.system.entity.Sleep;
import com.example.system.exception.CustomException;
import com.example.system.mapper.SleepMapper;
import com.example.system.mapper.UserMapper;
import com.example.system.service.ISleepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SleepServiceImpl extends ServiceImpl<SleepMapper, Sleep> implements ISleepService {
    @Autowired
    SleepMapper sleepMapper;
    @Autowired
    private UserMapper userMapper;

    public List<SleepDuration> findSleepByUserId(Integer userId) {
        return sleepMapper.findSleepByUserId(userId);
    }

    public void addSleepBySleep(Sleep sleep) {
        if (sleep.getUserId() == null) {
            throw new CustomException("用户Id不能为空");
        }
        if (!userMapper.existsUserById(sleep.getUserId())) {
            throw new CustomException("当前用户ID不存在");
        }
        if (sleepMapper.existsSleepKeyPair(sleep.getUserId(), sleep.getSleepId())) {
            throw new CustomException("健康表中已存在当前使用的复合键");
        }
        sleepMapper.addSleepBySleep(sleep);
    }

    public int deleteSleepBySleepId(Integer sleepId) {
        return sleepMapper.deleteSleepBySleepId(sleepId);
    }
}

